;;; Code:
(require 'flymake)

(defvar distopico:flymake-mode-line-error-counter
  `(:eval (distopico:flymake-maybe-show-counter :error t)))
(defvar distopico:flymake-mode-line-warning-counter
  `(:eval (distopico:flymake-maybe-show-counter :warning t)))
(defvar distopico:flymake-mode-line-note-counter
  `(:eval (distopico:flymake-maybe-show-counter :note t)))
(defvar distopico:flymake-current-counters '())

(setq flymake-no-changes-timeout 2 ;; seconds
      flymake-fringe-indicator-position 'right-fringe
      flymake-mode-line-counter-format
      '(""
	distopico:flymake-mode-line-error-counter
	distopico:flymake-mode-line-warning-counter
	distopico:flymake-mode-line-note-counter)
      flymake-mode-line-format
      '("["
	flymake-mode-line-title
	flymake-mode-line-counters
	"]"
	flymake-mode-line-exception))

(define-key flymake-mode-map (kbd "M-n") 'flymake-goto-next-error)
(define-key flymake-mode-map (kbd "M-p") 'flymake-goto-prev-error)
(define-key flymake-mode-map (kbd "C-c ! n") 'flymake-goto-next-error)
(define-key flymake-mode-map (kbd "C-c ! p") 'flymake-goto-prev-error)
(define-key flymake-mode-map (kbd "C-c ! d") 'flymake-show-buffer-diagnostics)
(define-key flymake-mode-map (kbd "C-c ! a") 'flymake-show-project-diagnostics)

;; Functions
(defun distopico:flymake-maybe-show-counter (type &optional space-l)
  "Filter if the `flymake' mode-line counter should be shown.
Only display the `TYPE' if have a number grater than 0 and
remove the space `SPACE-L' left if it is non-nil."
  (let* ((mline (flymake--mode-line-counter type t))
	 (counter (nth 1 mline))
	 (count (plist-get counter :propertize))
	 (countn (string-to-number (or count "")))
	 (has-counter (> countn 0))
	 (current-counters distopico:flymake-current-counters))
    (if has-counter
	(add-to-list 'distopico:flymake-current-counters type)
      (setq distopico:flymake-current-counters (remove type current-counters)))
    (when has-counter
      (cond (space-l (push '(:propertize " ") mline))
	    (t mline)))))

(defun distopico:flymake-enable-hook ()
  "Enable and setup `flymake' minor mode."
  (flymake-mode +1))

(put 'distopico:flymake-mode-line-error-counter 'risky-local-variable t)
(put 'distopico:flymake-mode-line-warning-counter 'risky-local-variable t)
(put 'distopico:flymake-mode-line-note-counter 'risky-local-variable t)
(put 'distopico:flymake-current-counters 'risky-local-variable t)

;; hooks
(add-hook 'prog-mode-hook #'distopico:flymake-enable-hook)

(provide 'conf-flymake)
;;; conf-flymake.el ends here
